package com.qfedu.servlet;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/3/30 15:15
 * 描述:
 */
@WebServlet("/testservlet")
public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        System.out.println("执行了!!! " + id);
        String json = "{\"id\":1,\"name\":\"李志\",\"age\":18,\"address\":\"中国北科\",\"clazz\":{\"id\":1,\"name\":\"2301\"}}";
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //如果前端时按照表单格式传递数据， req.getParameter 就可以获取参数
//        System.out.println(req.getParameter("id"));
////        System.out.println(req.getParameter("name"));
        //如果前端是 json串，则需要使用 输入流读取数据
        ServletInputStream is = req.getInputStream();
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(is,  Map.class);
        System.out.println(map);


        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().write("success");
    }
}
